<?php


namespace app\service\model;


use app\service\Y;

class AdminRoleModel extends BaseModel
{
    protected $table = 'admin_role';

    /**
     * 获取角色的权限集合
     * @param $roles
     * @return false|string[]
     */
    public static function getAuths($roles)
    {
        $role_auth_arr = self::where('id', 'in', $roles)->column('authoritys');
        $authorities = implode(',', $role_auth_arr);
        return explode(',', $authorities);
    }

    /**
     * 获取管理员对应的权限
     * @param $roleIds
     * @param string $type
     * @return array|string
     */
    public static function getAuthIds($roleIds, $type = 'str') {
        $authIds = self::where('id', 'in', (string)$roleIds)->where('status', '=', 1)->column('authoritys');
        $authIds = implode(',', $authIds);

        return $type == 'str' ?
            implode(',',array_unique(explode(',',$authIds))) : array_unique(explode(',',$authIds)); // 去除重复权限ID
    }

    /**
     * xmSelect组件格式数据
     * @param $admin_id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function xmSelectDate($admin_id): array
    {
        $initValue = explode(',', AdminModel::where('id', '=', $admin_id)->value('roles'));
        $data = self::field(['id as value', 'name'])->select();
        return [
            'data' => $data,
            'initValue' => $initValue
        ];
    }

    /**
     * 保存数据
     * @param $param
     * @param $id
     * @return bool|\think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function saveRole($param, $id) {
        if ($id > 0) {
            if (self::where('name', '=', $param['name'])->where('id', '<>', $id)->find()) {
                return Y::error('角色名已存在');
            }

            $role = self::find($id);
            if (!$role) {
                return Y::error('参数错误');
            }

            $role->save($param);
        } else {
            if (self::where('name', '=', $param['name'])->find()) {
                return Y::error('角色名已存在');
            }
            self::create($param);
        }
        return Y::success([], '保存成功');
    }
}